package yogaService

import (
	"duoke/model"
	"duoke/model/yogaModel"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/orm"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/os/gtime"
)

var Course = new(courseService)

type courseService struct{}

const TablesCourse = "yoga_course"

func (s *courseService) Info(c *gin.Context, id int) (*yogaModel.ReqCourse, error) {
	user, err := service.Request.User(c)
	if err != nil {
		return nil, err
	}
	var info yogaModel.ReqCourse
	session := orm.Db.NewSession()
	defer session.Close()
	get, err := session.Where("id=?", id).Table("yoga_course").Get(&info)
	if err != nil || !get {
		return nil, errors.New("获取课程信息不存在")
	}
	if user.Id > 0 {
		count, err := session.Where("class_id=? and user_id=?", info.Id, user.Id).
			Table("yoga_my_course").Count()
		if err == nil && count > 0 {
			info.IsBuy = 1
		}
	}
	// 已经过期了
	if int64(info.EndTime) < gtime.Now().Unix() {
		info.IsBuy = 3
	}
	return &info, err
}

func (s *courseService) Save(c *gin.Context, req yogaModel.ReqCourse) error {
	account, err := service.Request.Account(c)
	if err != nil {
		return errors.New("获取用户信息失败")
	}
	req.Acid = account.Id
	session := orm.Db
	var venue tables.YogaVenue
	get, err := session.Where("id=?", req.Id).Table("yoga_venue").
		Cols("name").Get(&venue)
	if err != nil || !get {
		return errors.New("场馆不存在")
	}
	req.VenueName = venue.Name
	if req.Id != 0 {
		update, err := session.Where("id=?", req.Id).Table(TablesCourse).AllCols().
			Omit("class_id").Update(req)
		if err != nil || update == 0 {
			return errors.New("修改失败")
		}
	} else {
		update, err := session.Table(TablesCourse).Insert(req)
		if err != nil || update == 0 {
			return errors.New("添加失败")
		}
	}
	return nil
}

func (s *courseService) List(c *gin.Context, req *model.ReqListV2) (*model.RspList, error) {
	user, err := service.Request.User(c)
	if err != nil {
		return nil, err
	}
	var m []yogaModel.ReqCourseJoin
	var count int64
	offset := (req.PageNo - 1) * req.PageSize
	table := orm.Db.Where("venue_id=?", req.FromId).Limit(req.PageSize, offset).
		Table(TablesCourse)
	if err != nil {
		return nil, errors.New("获取课程列表失败")
	}
	if user.Id > 0 {
		count, err = table.Alias("a").Join("LEFT", "yoga_my_course as b",
			"b.class_id=a.id and user_id=?", user.Id).Cols("a.*,b.class_id").
			OrderBy("a.id desc").
			FindAndCount(&m)
	} else {
		count, err = table.FindAndCount(&m)
	}
	for k, item := range m {
		if int64(item.EndTime) < gtime.Now().Unix() {
			m[k].ReqCourse.IsBuy = 3
		} else if item.ClassId != 0 {
			m[k].ReqCourse.IsBuy = 1
		}
	}

	return &model.RspList{
		Total: count,
		List:  &m,
	}, nil
}
